﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Runtime.CompilerServices;

namespace CygwinPackageManager.Common
{
	public abstract class PackageBaseDALC
	{
		private static Dictionary<string, int> _packageIDs;
		private static Dictionary<string, int> PackageIDs
		{
			[MethodImpl(MethodImplOptions.Synchronized)]
			get
			{
				if (_packageIDs == null)
					_packageIDs = new Dictionary<string, int>();

				return _packageIDs;
			}
		}

		[MethodImpl(MethodImplOptions.Synchronized)]
		public static int GetPackageID(string packageName)
		{
			Dictionary<string, int> packageIDs = PackageIDs;
			int packageID = 0;
			lock (packageIDs)
			{
				if (packageIDs.Count == 0)
				{
					packageID = 1;
					packageIDs.Add(packageName, packageID);
				}
				if (!packageIDs.ContainsKey(packageName))
				{
					packageID = packageIDs.Values.Max() + 1;
					packageIDs.Add(packageName, packageID);
				}
				else
				{
					packageID = packageIDs[packageName];
				}
			}

			return packageID;
		}
	}
}
